package com.hefan.api.controller.pub;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Controller
@RequestMapping("/pub/ImCc")
public class ReceiveImCcController {

	@Reference
	ONSProducer onsProducer;

	Logger logger = LoggerFactory.getLogger(ReceiveImCcController.class);
	
	/**
	 * IM抄送
	 * @Title: getMessageComments   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param request
	 * @return      
	 * @return: String
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年10月12日 下午4:36:25
	 */
	@RequestMapping("/receiveMsg")
	@ResponseBody
	public String getMessageComments(HttpServletRequest request) {
		ResultBean res = new ResultBean(200,"成功");
		try {
			//校验(暂不处理)
			// 接参
			String imCc = getBodyString(request.getReader());
			//定时队列，明天的2点开始投递
			Calendar cal=Calendar.getInstance();
			cal.add(Calendar.DATE,1);
			Date date = cal.getTime();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			long dstamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse( dateFormat.format(date)+" 02:00:00").getTime();
			long timeStamp = dstamp - System.currentTimeMillis();
			// 给队列发消息，完成后续工作
			Message message = new Message();
			message.put("imCc", imCc);
			message.setTopic(TopicRegistry.HEFANTV_IMCC);
			String onsEnv = DynamicProperties.getString("ons.env");
			message.setTag(onsEnv);
			onsProducer.sendDelayMsg(message,timeStamp);
			logger.info("IM抄回调成功");
			return JSON.toJSONString(res);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.info("IM抄回调失败");
			e.printStackTrace();
			return JSON.toJSONString(res);
		}
	}

	public static String getBodyString(BufferedReader br) {
		String inputLine;
		String str = "";
		try {
			while ((inputLine = br.readLine()) != null) {
				str += inputLine;
			}
			str = java.net.URLDecoder.decode(str, "utf-8");
			br.close();
		} catch (IOException e) {
			System.out.println("IOException: " + e);
		}
		return str;
	}
}
